<?php
/*
 *somment service
*/
namespace App\Service;

use App\Models\EwComment;
use App\Models\EwMember;
use App\Models\EwHouse;//房源
use App\Models\EwNews;//资讯
use App\Models\EwDeco;//装修
use App\Models\EwData;//数据
use App\Models\EwVideo;//视频
use App\Models\EwDecoComp;//装修公司
use App\Models\EwLogSys;

class CommentService extends BaseService
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否
	const GROUPS_SIZE = 1000;		//分组大小

	/**
	 * [getList 获取列表]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getList($params, $count = FALSE, $display = TRUE)
	{
		$params->member_id = property_exists($params,'member_id') ? $params->member_id : 0;
		$tableId = self::getTableId();
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['"' . $tableId . '" AS groupId,c.id,
			IFNULL((SELECT SUM(p.praise) AS up FROM App\Models\EwMemberPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $tableId . '),0) AS up,
			IFNULL((SELECT p.id AS praise_id FROM App\Models\EwMemberPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $tableId . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS up_id,0 AS sign_id,
			c.table_id,c.list_id,c.user_id,m.nickname,m.bg_image,m.avatar,c.replyer_id,r.nickname as replyer_name,c.content,c.groups,c.create_time']);
		// $builder->columns(['c.id,
		// 	IFNULL((SELECT SUM(p.praise) AS up FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . '),0) AS up,
		// 	IFNULL((SELECT SUM(p.praise) AS down FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . '),0) AS down,
		// 	IFNULL((SELECT p.id AS praise_id FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS up_id,
		// 	IFNULL((SELECT p.id AS praise_id FROM App\Models\EwPraise p WHERE p.praise = -1 AND c.id = p.list_id AND p.table_id = ' . $table_id . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS down_id,
		// 	c.table_id,c.list_id,c.user_id,m.nickname,m.bg_image,m.avatar,c.replyer_id,r.nickname as replyer_name,c.content,c.groups,c.is_del,c.create_time']);
		$builder->addFrom("App\Models\EwComment", 'c');
		$builder->leftJoin("App\Models\EwMember", 'c.user_id = m.id' , 'm');
		$builder->leftJoin("App\Models\EwMember", 'c.replyer_id = r.id' , 'r');
		$builder->orderBy("c.groups ASC");
		$builder->andWhere("c.is_del = " . self::DEL_FALSE);
		$builder->andWhere("c.groups >= 1000 ");

		if (isset($params->table_id) && $params->table_id && isset($params->list_id) && $params->list_id )
			$builder->andWhere("c.table_id = " . $params->table_id . " AND c.list_id = " . $params->list_id);

		//content
		if (isset($params->content) && $params->content)
			$builder->andwhere("c.content LIKE '%" . $params->content . "%'");

		if ($count)
			return $builder->getQuery()->execute()->count();

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();

		return $result->execute();

	}

	/**
	 * [getList 获取列表]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getSearch($params, $count = FALSE, $display = TRUE)
	{
		$tableId = self::getTableId();
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['c.id,
			IFNULL((SELECT SUM(p.praise) AS up FROM App\Models\EwMemberPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $tableId . '),0) AS up,
			IFNULL((SELECT p.id AS praise_id FROM App\Models\EwMemberPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $tableId . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS up_id,
			c.table_id,c.list_id,c.user_id,m.nickname,m.bg_image,m.avatar,c.replyer_id,r.nickname as replyer_name,c.content,c.groups,c.is_del,c.create_time']);
		// $builder->columns(['c.id,
		// 	IFNULL((SELECT SUM(p.praise) AS up FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . '),0) AS up,
		// 	IFNULL((SELECT SUM(p.praise) AS down FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . '),0) AS down,
		// 	IFNULL((SELECT p.id AS praise_id FROM App\Models\EwPraise p WHERE p.praise = 1 AND c.id = p.list_id AND p.table_id = ' . $table_id . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS up_id,
		// 	IFNULL((SELECT p.id AS praise_id FROM App\Models\EwPraise p WHERE p.praise = -1 AND c.id = p.list_id AND p.table_id = ' . $table_id . ' AND p.member_id = ' . intval($params->member_id) . ' ),0) AS down_id,
		// 	c.table_id,c.list_id,c.user_id,m.nickname,m.bg_image,m.avatar,c.replyer_id,r.nickname as replyer_name,c.content,c.groups,c.is_del,c.create_time']);
		$builder->addFrom("App\Models\EwComment", 'c');
		$builder->leftJoin("App\Models\EwMember", 'c.user_id = m.id' , 'm');
		$builder->leftJoin("App\Models\EwMember", 'c.replyer_id = r.id' , 'r');
		$builder->orderBy("c.groups ASC");
		$builder->andWhere("c.is_del = " . self::DEL_FALSE);

		if (isset($params->table_id) && $params->table_id && isset($params->list_id) && $params->list_id )
			$builder->andWhere("c.table_id = " . $params->table_id . " AND c.list_id = " . $params->list_id);

		//content
		if (isset($params->content) && $params->content)
			$builder->andwhere("c.content LIKE '%" . $params->content . "%'");

		if ($count)
			return $builder->getQuery()->execute()->count();

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();

		return $result->execute();

	}

	/**
	 * [getTableName 获取数据表名称]
	 * @return [type] [description]
	 */
	public static function getTableName()
	{
		$model = new EwComment;
		return $model->getSource();
	}

	/**
	 * [getTableId 获取数据表Id]
	 * @return [type] [description]
	 */
	public static function getTableId()
	{
		return ConfigsService::getTable(self::getTableName());
	}

	/**
	 * [getInfo 获取详情]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getInfo($id = 0)
	{
		$data = new \stdClass();
		$data->groupId = self::getTableId();
		$info = EwComment::findFirst($id)->toArray();
		foreach ($info as $key => $value) {
			$data->$key = $value;
		}
		return $data;
	}

	/**
	 * [getCommentInfo 获取评论详情]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getCommentInfo($id = 0)
	{
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['c.id,c.user_id,m.nickname,m.bg_image,m.avatar,c.replyer_id,r.nickname as replyer_name,c.content,c.groups,c.create_time']);
		$builder->addFrom("App\Models\EwComment", 'c');
		$builder->leftJoin("App\Models\EwMember", 'c.user_id = m.id' , 'm');
		$builder->leftJoin("App\Models\EwMember", 'c.replyer_id = r.id' , 'r');
		$builder->andWhere("c.id = " . $id);

		$result = $builder->getQuery()->execute()->toArray();

		$data = new \stdClass();
		$data->groupId = self::getTableId();
		if (is_array($result) && isset($result[0]) && is_array($result[0])){
			foreach ($result[0] as $key => $value) {
				$data->$key = $value;
			}
		}
		return $data;
	}

	/**
	 * [count 获取总数量]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function count($params)
	{
		return EwComment::count();
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$row = new EwComment;
		//回复
		if (isset($data->id) && $data->id){
			$info = EwComment::findFirst($data->id);

			//确认当前这条评论或回复存在
			if ($info){
				$row->table_id  = $info->table_id;
				$row->list_id = $info->list_id;
				$row->user_id = $data->member_id;
				$row->replyer_id = $info->user_id;
				$row->content = $data->content;
				$row->groups = self::getGroups($data->table_id, $data->list_id,$info->groups);
				if (!$row->groups){ //评论条数超过1000条则不能评论
					return NULL;
				}
				$row->is_del = self::DEL_FALSE;
			}else{
				//当前评论不存在
				return NULL;
			}
		//评论
		}else{
			$row->table_id = $data->table_id;
			$row->list_id = $data->list_id;
			$row->user_id = $data->member_id;
			$row->replyer_id = 0;
			$row->content = $data->content;
			$row->groups = self::getGroups($data->table_id, $data->list_id);
			$row->is_del = self::DEL_FALSE;
		}

		if ($row->save((array)$row)){
			//更新当前被评论的表评论量
			// self::updateTableComment($data);
			//评论成功返回评论的数据
			return self::getCommentInfo($row->id);
		}

	}

	/**
	 * [updateTableComment 更新当前被评论的表评论量]
	 * @param  [type] $data->table_id [数据表id]
	 * @param  [type] $data->list_id  [数据列id]
	 * @return [type]                 [description]
	 */
	private static function updateTableComment($data, $add = TRUE)
	{
		$add = $add ? 1 : -1;
		switch ($data->table_id) {
			case 1:
				if ($model = EwHouse::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			case 2:
				if ($model = EwNews::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			case 3:
				if ($model = EwDeco::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			case 4:
				if ($model = EwData::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			case 6:
				if ($model = EwVideo::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			case 7:
				if ($model = EwDecoComp::findFirst($data->list_id)){
					$model->comment = ($model->comment == 0) ? self::sum($data) : $model->comment + $add;
					return $model->save();
				}
				return NULL;
				break;

			default:
				return NULL;
				break;
		}
	}

	/**
	 * [sum 统计当前列表评论数量]
	 * @param  [type] $data->table_id [数据表id]
	 * @param  [type] $data->list_id  [数据列id]
	 * @param  [type] $countDel       [是否统计已删除的评论量 默认不统计]
	 * @return [type]                 [description]
	 */
	public static function sum($data, $countDel = FALSE)
	{

		$countDel = $countDel ? "" : 0;
		return EwComment::count([
			"table_id = :table_id: AND list_id = :list_id: AND is_del = :is_del:",
			"bind" => [
				"table_id" => $data->table_id,
				"list_id"  => $data->list_id,
				"is_del"   => $countDel
			],
		]);
	}

	/**
	 * [getGroups 获取评论的groups]
	 * @param  [type] $table_id   [description]
	 * @param  [type] $list_id    [description]
	 * @param  [type] $groups_now [description]
	 * @return [type]             [description]
	 */
	private static function getGroups($table_id, $list_id, $groups_now = NULL)
	{
		if ($groups_now){

			$groups_min = ($groups_now - $groups_now % self::GROUPS_SIZE);
			$groups_max = ($groups_now - $groups_now % self::GROUPS_SIZE + self::GROUPS_SIZE - 1);

			$info = EwComment::findFirst(['columns'=>'MAX(groups) AS groups','conditions' => 'table_id = ' . $table_id . ' AND list_id = ' . $list_id . ' AND groups >= ' . $groups_min . ' AND groups <= ' . $groups_max]);
			if ($info && intval($info->groups) + 1 < $groups_max){
				$groups = $info->groups + 1;
			}else{//评论条数超过1000条则不能评论
				$groups = NULL;
			}
		}else{
			$info = EwComment::findFirst(['columns'=>'MAX(groups) AS groups','conditions' => 'table_id = ' . $table_id . ' AND list_id = ' . $list_id]);
			if ($info)
				$groups = $info->groups - $info->groups % self::GROUPS_SIZE + self::GROUPS_SIZE;
		}
		return $groups;
	}

	/**
	 * [delete 移除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id, $member_id = FALSE)
	{

		if (isset($id) && $id)
			$data = EwComment::findFirst($id);
		if ($member_id){
			//会员只能删除自己的评论和回复
			if(intval($data->user_id) != intval($member_id)){
				return -1;
			}
		}
		if ($data){
			$data->is_del = self::DEL_TRUE;
			self::updateTableComment($data, FALSE);
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [restore 恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function restore($id)
	{
		if (isset($id) && $id)
			$data = EwComment::findFirst($id);

		if ($data){
			$data->is_del = self::DEL_FALSE;
			return $data->save();
		}

		return NULL;
	}


	/**
	 * [delete 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwComment::findFirst($id);

		if ($row)
			return $row->delete();

		return NULL;
	}
    /**
     * [makeSham 制作假的评论数据]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function makeShamComments($data)
    {
        $row = new EwComment;
        $row->table_id = $data->table_id;
        $row->list_id = $data->list_id;
        $row->user_id = $data->member_id;
        $row->replyer_id = 0;
        $row->content = $data->content;
        $row->groups = self::getGroups($data->table_id, $data->list_id);
        $row->is_del = self::DEL_FALSE;

        $row->save((array)$row);

    }
    public static function addOperateLog($record){
        $row = new EwLogSys;
        $row->save($record);
    }
}